﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Threading;

namespace Amazon.PAAPI
{
    class AmazonDownloader
    {
        private AmazonCategory[] categories = new AmazonCategory[] { new AmazonCategory("Books", "1000", 4) };
        public void runDownload()
        {
            ManualResetEvent[] mres = new ManualResetEvent[categories.Length];
            int i;
            BackgroundWorker[] categoryWorkers = new BackgroundWorker[categories.Length];
            for (i = 0; i < categoryWorkers.Length; i++)
            {
                int j = i;
                mres[i] = new ManualResetEvent(false);
                categoryWorkers[i] = new BackgroundWorker();
                categoryWorkers[i].DoWork += downloadCategory;
                categoryWorkers[i].RunWorkerCompleted += (sender, args) => mres[j].Set();
                categoryWorkers[i].RunWorkerAsync(categories[i]);

            }
            WaitHandle.WaitAll(mres);
        }
        
        private void downloadCategory(object sender, DoWorkEventArgs e)
        {
            AmazonCategoryRequest creq = new AmazonCategoryRequest((AmazonCategory)e.Argument);
            creq.Run();
        }
        
    }
}
